﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Primitives3D;
using Microsoft.Xna.Framework;
using System.Diagnostics;
using TrianglePicking;
using Microsoft.Xna.Framework.Graphics;
//using System.Windows.Forms;

namespace LevelEditor
{
    class XnaCanvas : GraphicsDeviceControl
    {

        public float yaw = 0;   //x
        public float pitch = 0; //y
        float roll = 0;  //z

        public int mouseX = 0;
        public int mouseY = 0;

        public System.Windows.Forms.TextBox textbox;

        public float intersection = 1;

        Stopwatch timer;

        public float time = 0;


        protected override void Initialize()
        {
            timer = Stopwatch.StartNew();
            //Application.Idle += delegate { Invalidate(); };



        }

        protected override void Draw()
        {
            //GraphicsDevice.Clear(Color.CornflowerBlue);
            /*
            VertexPositionColor[] drawableTriangle =
                    {
                        new VertexPositionColor(new Vector3(-1, -1, 0), Color.Black),
                        new VertexPositionColor(new Vector3( 1, -1, 0), Color.Black),
                        new VertexPositionColor(new Vector3( 0,  1, 0), Color.Black)
                    };

            GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, drawableTriangle, 0, 1);
            */


            CubePrimitive cube = new CubePrimitive(GraphicsDevice);

            Vector3 cameraPosition = new Vector3(0, 0, 4.5f);
            float aspect = GraphicsDevice.Viewport.AspectRatio;

            Matrix worldMatrix = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll);
            Matrix viewMatrix = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
            Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(1, aspect, 1, 10);

            Pickable picky = new Pickable(cube.GetVerticesAsVectors(), cube.BoundingSphere);

            Pickable[] models = new Pickable[] { picky };
            Matrix[] modelWorldTransforms = new Matrix[] { worldMatrix };

            

            PickingInformation result = PickingHelper.UpdatePicking(projectionMatrix, viewMatrix, GraphicsDevice.Viewport, new Vector2(mouseX, mouseY), models, modelWorldTransforms);

            Color color = Color.Red;

            if (result != null)
            {
                //System.Diagnostics.Debug.WriteLine(result);
                
                // Draw the triangle.
                color = Color.Blue;
                 
            }
            
            
            
            
            cube.Draw(worldMatrix, viewMatrix, projectionMatrix, color);
        }
    }
}
